<template>
  <div class='adduser'>
    <el-dialog :title=title @close="close"
    :visible.sync="dialogVisible"
    class="title" :close-on-click-modal="false">
      <el-form :model="numberValidateForm" ref="numberValidateForm"
      label-width="66px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username"
        class="w-[242px] inline-block mr-[10px]"
        :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
          ]">
          <el-input v-model="numberValidateForm.username"></el-input>
        </el-form-item>
        <el-form-item
          class="w-[242px] inline-block"
          label="电话"
          prop="phone"
          :rules="[
            { required: true, message: '电话不能为空', trigger: 'blur'},
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur'}
          ]"
        >
          <el-input v-model.number="numberValidateForm.phone"></el-input>
        </el-form-item>
         <el-form-item label="昵称" prop="nickName"
          class="w-[242px] inline-block mr-[10px]"
          :rules="[
              { required: true, message: '请输入昵称', trigger: 'blur' },
              { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
            ]">
            <el-input v-model="numberValidateForm.nickName"></el-input>
        </el-form-item>
        <el-form-item
          class="w-[242px] inline-block"
          prop="email"
          label="邮箱"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ]">
          <el-input v-model="numberValidateForm.email"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="dept.id" class="w-[242px] inline-block  mr-[10px]">
          <treeselect
          v-model="numberValidateForm.dept.id"
           :options="options" placeholder="选择部门"
           :flatten-search-results="true"
          :load-options="loadOptions"/>
        </el-form-item>
        <el-form-item label="岗位" prop="jobs"  class="w-[242px] inline-block">
          <treeselect
          v-model="numberValidateForm.jobs" multiple
          :options="jobs" placeholder="选择岗位"
          :flatten-search-results="true"/>
        </el-form-item>
        <el-form-item label="性别" prop="gender" class="inline-block mr-[75px]">
         <div class="w-[110px]">
            <el-radio-group v-model="numberValidateForm.gender">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
         </div>
        </el-form-item>
         <el-form-item label="状态" prop="enabled" class="inline-block">
          <el-radio-group v-model="numberValidateForm.enabled" size="medium">
            <el-radio v-for="(item, index) in enabledOptions" :key="index" :label="item.value"
              :disabled="item.disabled">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <treeselect
          v-model="numberValidateForm.roles" multiple
          :options="allroles" placeholder="请选择"
          :flatten-search-results="true" class="w-[430px]"/>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm(numberValidateForm)" class="text-[12px]">取消</el-button>
          <el-button type="primary" @click="submitForm(numberValidateForm)"
          class="text-[12px]">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { Treeselect, LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getDept, getSuperior } from '@/api/dept'
import { getAllroles } from '@/api/roles'
import { getJob } from '@/api/job'
import { postUser, putUser, getUser } from '@/api/user'
export default {
  name: 'Adduser',
  data () {
    return {
      dialogVisible: false, // 控制弹出层显示隐藏
      numberValidateForm: {
        username: '',
        phone: null,
        nickName: '',
        email: '',
        gender: '男', // 性别
        enabled: false, // 状态
        dept: {
          id: null
        },
        roles: [],
        jobs: []
      },
      options: [],
      allroles: [],
      jobs: [],
      title: '新增用户',
      isEdit: false, // 是否编辑
      enabledOptions: [{
        label: '激活',
        value: true
      }, {
        label: '禁用',
        value: false
      }],
      id: null
    }
  },
  components: {
    Treeselect
  },
  computed: {},
  watch: {
  },
  mounted () {
    this.getDept()
    this.getAllroles()
    this.getJob()
  },
  methods: {
    // 关闭弹出层
    close () {
      this.dialogVisible = false
      this.$refs.numberValidateForm.resetFields()
    },
    // 开启弹出层
    open (isEdit = false, data) {
      // data会被缓存起来
      this.dialogVisible = true
      isEdit ? this.title = '修改用户' : this.title = '新增用户'
      isEdit && this.handleEditUser(data)
      isEdit && this.getDeptSuperior(data.dept.id)
      this.isEdit = isEdit
    },
    // 展示编辑用户的操作
    handleEditUser (data) {
      getUser({ id: data.id }).then(res => {
        const content = res.content[0]
        const _data = this.numberValidateForm
        for (const key in _data) {
          if (key !== 'roles' && key !== 'job') {
            _data[key] = content[key]
          }
        }
        this.id = content.id
        _data.jobs = content.jobs.map(item => item.id)
        _data.roles = content.roles.map(item => item.id)
      })
    },
    // 查询部门:根据ID获取同级与上级数据
    getDeptSuperior (id) {
      getSuperior([id]).then(res => {
        this.options = res.content.map(item => {
          if (item.hasChildren && !item.children) item.children = null
          return item
        })
      })
    },
    // 提交表单信息
    submitForm () {
      if (!this.numberValidateForm) return
      const params = JSON.parse(JSON.stringify(this.numberValidateForm))
      params.jobs = params.jobs.map(id => ({ id }))
      params.roles = params.roles.map(id => ({ id }))
      // 新增成功后。
      // 1. 关闭弹出层
      // 2. 刷新列表
      this.isEdit ? this.editUser(params) : this.addUser(params)
    },
    // 新增方法
    addUser (params) {
      postUser(params).then(res => {
        this.$message.success('新增成功')
        this.close()
        this.$emit('handelSuccess')
      })
    },
    // 修改方法
    editUser (params) {
      params.id = this.id
      putUser(params).then(res => {
        this.$message.success('修改成功')
        this.close()
        this.$emit('handelSuccess')
      })
    },
    resetForm (formName) {
      this.close()
      // resetFields 清空表单（只能清空动态的值）
      // data传过来的值是静态，有缓存的
      this.$refs.numberValidateForm.resetFields()
    },
    // 部门默认加载
    getDept () {
      // 初始化数据 只加载根节点
      getDept().then(res => {
        this.options = res.content.map(item => {
          if (item.hasChildren) item.children = null
          return item
        })
      })
    },
    loadOptions ({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        // 加载点击节点的 子节点
        getDept({ pid: parentNode.id, enabled: true }).then(res => {
          parentNode.children = res.content.map(item => {
            if (item.hasChildren) item.children = null
            return item
          })
        })
        callback()
      }
    },
    //  角色
    getAllroles () {
      getAllroles({ enabled: true }).then(res => {
        for (const index of res) {
          const modeInfo = {}
          modeInfo.id = index.id
          modeInfo.label = index.name
          this.allroles.push(modeInfo)
        }
      })
    },
    // 部门
    getJob () {
      getJob({ enabled: true }).then(res => {
        for (const index of res.content) {
          const modeInfo = {}
          modeInfo.id = index.id
          modeInfo.label = index.name
          this.jobs.push(modeInfo)
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.el-dialog__body{
  display: flex;
}
::v-deep .el-form-item {
  text-align: right;
  .el-form-item__label {
    text-align: right;
    font-size: 14px;
    color: #606266;
    font-weight: 700;
  }
}
::v-deep .el-input__inner,::v-deep .vue-treeselect__control{
  height: 32px;
  line-height: 32px;
}
.title ::v-deep .el-dialog{
  width: 570px;
}
.el-form-item {
  margin-bottom: 18px;
}
</style>
